package com.vlong.town.controller.admin.wxUser;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vlong.town.controller.base.BaseController;
import com.vlong.town.entity.wxUser.WxUser;
import com.vlong.town.service.wxUser.WxUserService;
import com.vlong.town.util.date.DateUtil;
import com.vlong.town.util.pagination.PageTag;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.List;

/**
 * 微信用户管理Controller
 * @author Assassin
 */
@Controller
@RequestMapping("/wxUser")
public class WxUserController extends  BaseController{
	
	
	@Autowired
	private  WxUserService  wxUserService;//微信用户接口
	
	 /**
     * 进入微信用户列表页面
     * @param pageNo 当前页码
     * @param pageSize 每页记录数
     * @return user/list_user
     */
    @RequestMapping("/list")
    public String gotoWxUserListPage(
            @RequestParam(required=false, value="pageNo") Integer pageNo,
            @RequestParam(required=false, value="pageSize") Integer pageSize,
            @RequestParam(required=false, value="wxName") String wxName,
            @RequestParam(required=false, value="realName") String realName,
            @RequestParam(required=false, value="telphone") String telphone) {
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
        PageHelper.orderBy("update_time DESC");
        List<WxUser> wxUserList = this.wxUserService.queryList(null, 1, 1, 1L, null, wxName, null,null, realName, null, null,telphone, null, null, null, null, null);
        PageInfo<WxUser> pageInfo = new PageInfo<WxUser>(wxUserList);
        PageTag<WxUser> pt = new PageTag<WxUser>(request, "list", pageInfo);
        request.setAttribute("pageHtml", pt.getPageHtml());
        request.setAttribute("realName", realName);
        request.setAttribute("telphone", telphone);
        request.setAttribute("wxName", wxName);
        request.setAttribute("wxUserList", wxUserList);
        return "admin/wxUser/list_wxUser";
    }

    /**
     * 导出客户统计信息数据到Excel
     * @param wxName 微信名称
     * @param realName 用户名称
     * @param telPhone 手机号码
     * @return Excel File
     * @throws Exception
     */
    @PostMapping("/exportUser")
    public ModelAndView exportUser(
            @RequestParam(required=false, value="wxName_user") String wxName,
            @RequestParam(required=false, value="realName_user") String realName,
            @RequestParam(required=false, value="telPhone_user") String telPhone
    ) throws Exception {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("客户统计");
        // 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
        sheet.setColumnWidth((short) 0, (short) (15.7 * 150));
        sheet.setColumnWidth((short) 1, (short) (25.7 * 150));
        sheet.setColumnWidth((short) 2, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 3, (short) (35.7 * 150));
        Row row = sheet.createRow((short) 0);
        // 创建两种单元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 创建第一种字体样式
        f.setFontHeightInPoints((short) 12);
        f.setColor(IndexedColors.BLACK.getIndex());
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        // 创建第二种字体样式
        f2.setFontHeightInPoints((short) 11);
        f2.setColor(IndexedColors.BLACK.getIndex());
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        // 设置第一种单元格的样式
        cs.setFont(f);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        // 设置第二种单元格的样式
        cs2.setFont(f2);
        cs2.setBorderLeft(CellStyle.BORDER_THIN);
        cs2.setBorderRight(CellStyle.BORDER_THIN);
        cs2.setBorderTop(CellStyle.BORDER_THIN);
        cs2.setBorderBottom(CellStyle.BORDER_THIN);
        cs2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        // 创建列（每行里的单元格）
        Cell cell = row.createCell(0);
        cell.setCellValue("微信名称");
        cell.setCellStyle(cs);

        cell = row.createCell(1);
        cell.setCellValue("用户姓名");
        cell.setCellStyle(cs);

        cell = row.createCell(2);
        cell.setCellValue("联系电话");
        cell.setCellStyle(cs);

        cell = row.createCell(3);
        cell.setCellValue("注册时间");
        cell.setCellStyle(cs);

        // 查询要导出的客户统计数据
        List<WxUser> wxUserList = this.wxUserService.queryList(null, 1, 1, 1L, null, wxName, null,null, realName, null, null,telPhone, null, null, null, null, null);
        for(int i = 0; i < wxUserList.size(); i++) {
            WxUser wxUser = wxUserList.get(i);

            row = sheet.createRow(i + 1);
            cell = row.createCell(0);
            cell.setCellValue(wxUser.getWxName());
            cell.setCellStyle(cs2);

            cell = row.createCell(1);
            cell.setCellValue(wxUser.getUserName());
            cell.setCellStyle(cs2);

            cell = row.createCell(2);
            cell.setCellValue(wxUser.getTelphone());
            cell.setCellStyle(cs2);

            cell = row.createCell(3);
            cell.setCellValue(DateUtil.formatDateTime(wxUser.getCreateTime()));
            cell.setCellStyle(cs2);

        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("客户统计" + ".xls").getBytes(), "ISO-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }
}
